package com.sgcc.ln.pmos.common.base;

import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.WindowManager;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ActivityUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.ConfirmPopupView;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.sgcc.ln.pmos.arouter.app.AppArouterPath;
import com.sgcc.ln.pmos.common.bean.EventCenter;
import com.sgcc.ln.pmos.common.dialog.CommonDialog;
import com.sgcc.ln.pmos.common.dialog.LoadingDialogUtils;
import com.sgcc.ln.pmos.common.utils.ImmersionBarUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import me.jessyan.autosize.AutoSizeCompat;
import me.jessyan.autosize.AutoSizeConfig;


/**
 * 项目通用父类
 *
 * @author
 */
public abstract class BaseActivity extends FragmentActivity {

    protected Context mContext = null;
    boolean IS_ICS_OR_LATER = false;

    /**
     * 是否竖屏锁定
     *
     * @return
     */
    public boolean isFixedScreenOrientation() {

        return true;
    }

    /**
     * 是否绑定EventBus
     *
     * @return
     */
    public boolean isBindEventBusHere() {
        return false;
    }

    /**
     * 设置布局ID
     *
     * @return
     */
    protected abstract int getContentViewLayoutID();

    /**
     * 初始化布局以及监听事件
     */
    protected void initViews() {

    }

    /**
     * 初始化业务操作
     */
    protected void initData() {

    }

    /**
     * 是否自己处理onCreate逻辑
     *
     * @return
     */
    protected boolean isCustomCreate() {
        return false;
    }

    /**
     * 自定义初始化。如果{@link #isCustomCreate()}为true的时候调用
     *
     * @param savedInstanceState
     */
    protected void customInit(Bundle savedInstanceState) {

    }

    /**
     * EventBus 回调方法
     *
     * @param eventCenter
     */
    public void onEventCallBack(EventCenter eventCenter) {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        ImmersionBarUtils.initBaseBar(this);
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        if (isFixedScreenOrientation()) {
            // 竖屏锁定
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        mContext = this;
        //是否绑定了EventBus
        if (isBindEventBusHere()) {
            EventBus.getDefault().register(this);
        }

        if (!isCustomCreate()) {
            setContentView(getContentViewLayoutID());
            receiveIntentExtras();
            initViews();
            initData();
        } else {
            customInit(savedInstanceState);
        }
    }

    /**
     * 用来再请求前接收和初始化
     */
    protected void receiveIntentExtras() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkWifiProxy();
    }


    public void checkWifiProxy() {
        IS_ICS_OR_LATER = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
        String proxyAddress;
        int proxyPort;
        if (IS_ICS_OR_LATER) {
            proxyAddress = System.getProperty("http.proxyHost");
            String portStr = System.getProperty("http.proxyPort");
            proxyPort = Integer.parseInt(!TextUtils.isEmpty(portStr) ? portStr : "-1");
        } else {
            proxyAddress = android.net.Proxy.getHost(this);
            proxyPort = android.net.Proxy.getPort(this);
        }
        if ((!TextUtils.isEmpty(proxyAddress) && proxyPort != -1)) {
            showErrorDialog();
        }
    }


    @Override
    public boolean moveTaskToBack(boolean nonRoot) {
        return super.moveTaskToBack(true);
    }

    public void showErrorDialog() {
        showErrorDialog(true);
    }

    public void showErrorDialog(boolean finish) {
        CommonDialog dialog = new CommonDialog(this);
        dialog.setTitle("警告");
        dialog.setMessage("当前处于非法操作，请退出后重试！");
        dialog.setPositive("确定");
        dialog.setSingle(true);
        dialog.setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                dialog.dismiss();
            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (finish)
                    ActivityUtils.finishAllActivities();
            }
        });
        dialog.show();
    }


    /**
     * 当前Activity Or Fragment 注册 如有EventBus回调 则会回调到此方法
     *
     * @param eventCenter
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventCenter eventCenter) {
        if (null != eventCenter) {
            onEventCallBack(eventCenter);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 如果当前Activity注册了EventBus 则取消注册
        try {
            if (isBindEventBusHere()) {
                EventBus.getDefault().unregister(this);
            }

        } catch (Exception e) {
        }
    }

    public void showLoading() {
        LoadingDialogUtils.showLoadingDialog(this);
    }

    public void showLoading(String msg) {
        LoadingDialogUtils.showLoadingDialog(this, msg);
    }

    public void dismissLoading() {
        LoadingDialogUtils.dismissLoadingDialog(this);
    }

    public RecyclerView.ItemDecoration getRecyclerViewDivider(@DrawableRes int drawableId) {
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(getResources().getDrawable(drawableId));
        return itemDecoration;
    }

    /**
     * @author yinsh
     * @description 是否取消适配
     * @date 2021/9/18 下午4:08
     */
    public boolean isCancelAdpt() {
        return false;
    }


    /**
     * 重写 getResource 方法，防止系统字体影响
     */
    @Override
    public Resources getResources() {
        if (!isCancelAdpt()) {
            int width = 375;
            try {
                width = AutoSizeConfig.getInstance().getDesignWidthInDp();
            } catch (Exception e) {
                AutoSizeConfig.getInstance().setDesignWidthInDp(width);
            }

            if (AutoSizeConfig.getInstance().getScreenWidth() <= 0) {
                try {
                    Thread.sleep(16);
                } catch (InterruptedException e) {
                }
            }
            AutoSizeCompat.autoConvertDensityOfGlobal(super.getResources());//如果没有自定义需求用这个方法
        }
        return super.getResources();
    }


    public void goMainActivity() {
        ARouter.getInstance()
                .build(AppArouterPath.APP_MAIN)
                .navigation();
    }


    private long LAST_CLICK_TIME; // 上一次点击事件

    private boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        // 两次点击间隔不能少于500ms
        if ((currentClickTime - LAST_CLICK_TIME) >= 300) {
            flag = false;
        }
        LAST_CLICK_TIME = currentClickTime;
        return flag;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 判断连续点击事件时间差
            if (!allowMultiClick() && isFastClick()) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 是否允许多次点击
     *
     * @return 默认false，子类可以重写
     */
    public boolean allowMultiClick() {
        return false;
    }


    private ConfirmPopupView confirmPopupView;

    public void showLogoutDialog() {
        if (confirmPopupView == null) {
            confirmPopupView = new XPopup.Builder(mContext)
                    .asConfirm("下线通知", "您的账号在其他设备上登录，您被迫下线了，如果这不是您本人的操作，那么您的密码可能已经泄露，建议您修改密码。",
                            "知道了", "重新登录",
                            new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    ARouter.getInstance()
                                            .build(AppArouterPath.APP_LOGIN)
                                            .navigation();

                                }
                            }, new OnCancelListener() {
                                @Override
                                public void onCancel() {
                                    goMainActivity();
                                }
                            }, false);
        }
        confirmPopupView.show();
    }
}
